package com.ruoyi.web.controller.system;

import java.time.LocalDate;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.OutputStringList;
import cn.wildfirechat.sdk.RelationAdmin;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.system.domain.vo.GroupAssistantSelectVo;
import com.ruoyi.system.domain.vo.GroupAssistantVo;
import com.ruoyi.system.dto.GroupAssistantDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TUser;
import com.ruoyi.system.domain.TUserStatus;
import com.ruoyi.system.domain.vo.TUserVo;
import com.ruoyi.system.service.ITUserService;
import com.ruoyi.system.service.ITUserStatusService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * APP用户Controller
 * 
 * @author ruoyi
 * @date 2025-08-18
 */
@RestController
@RequestMapping("/system/tuser")
@Api("APP用户")
public class TUserController extends BaseController
{
    @Autowired
    private ITUserService tUserService;

    @Autowired
    private ITUserStatusService tUserStatusService;

    /**
     * 查询用户列表
     */
    @ApiOperation(value = "用户列表")
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    @Anonymous
    public TableDataInfo list(TUser tUser)
    {
        // 手动分页以确保count查询准确性
        startPage();
        if (tUser.getDeleted() == null){
            tUser.setDeleted(0L);
        }
        List<TUserVo> list = tUserService.selectTUserVoList(tUser);
        
        // 获取准确的总数
        int total = tUserService.countTUserList(tUser);
        
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);
        
        return rspData;
    }

    /**
     * 导出APP用户列表
     */
    @ApiOperation(value = "导出APP用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @Log(title = "APP用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TUser tUser)
    {
        List<TUser> list = tUserService.selectTUserList(tUser);
        ExcelUtil<TUser> util = new ExcelUtil<TUser>(TUser.class);
        util.exportExcel(response, list, "APP用户数据");
    }

    /**
     * 获取APP用户详细信息
     */
    @ApiOperation(value = "获取APP用户详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tUserService.selectTUserById(id));
    }

    /**
     * 新增APP用户
     */
    @ApiOperation(value = "新增APP用户")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "APP用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TUser tUser) throws Exception {
        return toAjax(tUserService.insertTUser(tUser));
    }

    /**
     * 修改APP用户
     */
    @ApiOperation(value = "修改APP用户")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "APP用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TUser tUser)
    {
        return toAjax(tUserService.updateTUser(tUser));
    }

    /**
     * 删除APP用户
     */
    @ApiOperation(value = "删除APP用户")
    @Log(title = "APP用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String id)
    {
        return toAjax(tUserService.deleteTUserById(id));
    }

    /**
     * 获取用户状态
     */
    @ApiOperation(value = "获取用户状态")
    @GetMapping("/status/{uid}")
    public AjaxResult getUserStatus(@PathVariable("uid") String uid)
    {
        TUserStatus userStatus = tUserStatusService.selectTUserStatusByUid(uid);
        if (userStatus == null) {
            // 如果没有状态记录，默认为正常状态
            userStatus = new TUserStatus();
            userStatus.setUid(uid);
            userStatus.setStatus(0); // 0 正常
            userStatus.setDt(System.currentTimeMillis());
        }
        return success(userStatus);
    }

    /**
     * 设置用户状态
     */
    @ApiOperation(value = "设置用户状态")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "设置用户状态", businessType = BusinessType.UPDATE)
    @PostMapping("/status")
    public AjaxResult setUserStatus(@RequestBody TUserStatus userStatus)
    {
        return toAjax(tUserStatusService.setUserStatus(userStatus.getUid(), userStatus.getStatus()));
    }


    /**
     * 查询禁用用户列表（状态为禁言或封禁的用户）
     */
    @ApiOperation(value = "查询禁用用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/disabled")
    public TableDataInfo listDisabledUsers(TUser tUser)
    {
        tUser.setDisabled(1);
        // 手动分页以确保count查询准确性
        startPage();
        if (tUser.getDeleted() == null){
            tUser.setDeleted(0L);
        }
        List<TUserVo> list = tUserService.selectTUserVoListByDisabled(tUser);
        // 获取准确的总数
        int total = tUserService.countTUserVoListByDisabled(tUser);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);

        return rspData;
    }

    @ApiOperation(value = "新增群助手用户")
    @PostMapping("/insertGroupHelper")
    public AjaxResult insertGroupHelper(@RequestBody GroupAssistantVo groupAssistant)
    {
        return success(tUserStatusService.insertGroupHelper(groupAssistant));
    }


    @ApiOperation(value = "删除群助手用户")
    @GetMapping("/deleteGroupHelper/{id}")
    public AjaxResult deleteGroupHelper(@PathVariable("id") Long id)
    {
        return success(tUserStatusService.deleteGroupHelper(id));
    }


    @ApiOperation(value = "查询群助手用户")
    @GetMapping("/selectGroupHelper")
    public TableDataInfo selectGroupHelper(GroupAssistantSelectVo selectVo)
    {
        startPage();
        List<GroupAssistantDTO> groupAssistantDTOS = tUserStatusService.selectGroupHelper(selectVo);
        return getDataTable(groupAssistantDTOS);
    }

    @ApiOperation(value = "查询是否有群助手权限")
    @GetMapping("/checkGroupHelper/{id}")
    @Anonymous
    public AjaxResult checkGroupHelper(@PathVariable String id)
    {
        // 获取当前年月日
        LocalDate now = LocalDate.now();
        int checkGroupHelper = tUserStatusService.checkGroupHelper(id,now);
        return success(checkGroupHelper != 0);
    }


    @ApiOperation(value = "获取好友列表")
    @GetMapping("/getFriendList/{uid}")
    public AjaxResult addPCLoginUser(@PathVariable String uid)
    {
        try {
            IMResult<OutputStringList> list = RelationAdmin.getFriendList(uid);
            if (list != null && list.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS ){
                OutputStringList result = list.getResult();
                List<String> uids = result.getList();
                if (uids == null || uids.isEmpty()){
                    return success();
                }
                // 获取用户信息
                List<TUserVo>  tUserVos = tUserService.getUserList(uids);
                return success(tUserVos);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return success();
    }

}
